package com.base.leetcode;

import com.base.dataStructure.stack.ArrayStack;

/**
 * @Author: hdhao
 * @Create: 2023/4/1 - 17:24
 * @Version: v1.0
 */
//有效的括号
public class Leetcode20 {
    /**
     * 遇到左括号,就把要配对的右括号放入栈顶
     * 遇到右括号,就把它与栈顶元素对比
     *      若相等,栈顶元素弹出,继续对比下一组
     *      若不等,无效括号,直接返回false
     * @param s
     * @return
     */
    public boolean isValid(String s){
        ArrayStack<Character> stack = new ArrayStack<>(s.length());
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == '('){
                stack.push(')');
            }else if (c == '['){
                stack.push(']');
            }else if (c == '{'){
                stack.push('}');
            }else {
                if (!stack.isEmpty() && c == stack.peek()){
                    stack.pop();
                }else {
                    return false;
                }
            }
        }
        return stack.isEmpty();
    }

    public static void main(String[] args) {
        Leetcode20 s = new Leetcode20();
        System.out.println(s.isValid("{()}"));
        System.out.println(s.isValid("{(})"));
        System.out.println(s.isValid("[{(])}"));
        System.out.println(s.isValid("[{()}]"));
    }
}
